package com.zhoug.widget.round;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;

/**
 * 圆角组件工具,用于把组件canvas裁剪成圆角
 * 在View的对应方法中调用同名方法
 * @Author 35574
 * @Date 2020/7/2
 * @Description
 */
public class RoundHelper {
    private float width, height;
    /**
     * 角度 默认10
     */
    private int corners = 10;
    /**
     * 是否为圆形:为true时corners属性无效
     */
    private boolean circular;

    //半径
    private float radius;
    // 圆形路径
    private Path path;
    private Paint mPaint;

    public RoundHelper(int corners, boolean circular) {
        this.corners = corners;
        this.circular = circular;
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setAntiAlias(true);
    }

    public void onSizeChanged(int width, int height) {
        this.width = width;
        this.height = height;
        radius = width < height ? width >> 1 : height >>1;
        if(corners>radius){
            corners= (int) radius;
        }
        path=null;
    }

    public Path getPath() {
        if (path == null) {
            path = new Path();
            //圆
            if (circular) {
                path.addCircle(width / 2, height / 2, radius, Path.Direction.CW);
            } else {
                //圆角
                path.moveTo(corners, 0);
                path.lineTo(width - corners, 0);
                //二次贝塞尔
                path.quadTo(width, 0, width, corners);
                path.lineTo(width, height - corners);
                path.quadTo(width, height, width - corners, height);
                path.lineTo(corners, height);
                path.quadTo(0, height, 0, height - corners);
                path.lineTo(0, corners);
                path.quadTo(0, 0, corners, 0);
            }
        }

        return path;
    }

    /**
     * 在View.onDraw()方法中调用,然后调用View的super.onDraw(canvas);
     * @param canvas
     */
    public void clipRound(Canvas canvas) {
        if (width > corners && height > corners) {
            canvas.clipPath(getPath());
        }
    }

    public void drawBorder(Canvas canvas,int borderWidth,int borderColor){
        if (borderWidth > 0) {
            mPaint.setStrokeWidth(borderWidth);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setColor(borderColor);
            canvas.drawPath(getPath(), mPaint);
        }
    }

    public void drawBgColor(Canvas canvas,int color){
            mPaint.setStyle(Paint.Style.FILL);
            mPaint.setColor(color);
            canvas.drawPath(getPath(), mPaint);

    }

    public int getCorners() {
        return corners;
    }

    public void setCorners(int corners) {
        this.corners = corners;
    }

    public boolean isCircular() {
        return circular;
    }

    public void setCircular(boolean circular) {
        this.circular = circular;
    }


}
